﻿Public Class ProcessItem
    Inherits ObservableImpl
    Implements NamedStatusObservable
    Implements Observer
    Implements Resetable
    Private status As ProcessItemStatus = ProcessItemStatus.Idle
    Private name As String
    Private commandList = New List(Of Command)


    Sub New(ByVal aName As String)
        name = aName
    End Sub

    Public Function getStatusDescription() As String Implements NamedStatusObservable.getStatusDescription
        Select Case status
            Case ProcessItemStatus.Idle
                Return "Idle"
            Case ProcessItemStatus.Processing
                Return "Processing"
            Case ProcessItemStatus.Finalized
                Return "Finalized"
        End Select
        Return ""
    End Function

    Sub addCommand(ByVal command As Command)
        commandList.add(command)
        command.Register(Me)
    End Sub

    Function getName() As String Implements NamedStatusObservable.getName
        Return name
    End Function


    Sub Notify() Implements Observer.Notify
        If allCommandsDone() Then
            status = ProcessItemStatus.Finalized
        Else
            status = ProcessItemStatus.Processing
        End If
        NotifyObservers()
    End Sub

    Private Function allCommandsDone() As Boolean
        For Each Command In commandList
            If Command.executionFinalized() Then
                Command.unregister(Me)
            Else
                Return False
            End If
        Next
        Return True
    End Function

    Public Sub reset() Implements Resetable.reset
        status = ProcessItemStatus.Idle
        resetCommands()
        Notify()
    End Sub

    Private Sub resetCommands()
        For Each Command In commandList
            Command.reset()
            Command.UnRegister(Me)
            Command.register(Me)
        Next
    End Sub

    Public Function isDone() As Boolean
        Return status = ProcessItemStatus.Finalized
    End Function

    Public Function getCommandList() As List(Of Command)
        Return commandList
    End Function

    Public Function numberOfCompletedCommands() As Integer
        Dim completedCommands = 0
        For Each Command In commandList
            If Command.hasFinalized() Then
                completedCommands += 1
            End If
        Next
        Return completedCommands
    End Function


End Class
